<?php

/*
 * Categorias
*/

class Categorias extends Controller {
    public $lenguaje='spanish';

    function Categorias() {
        parent::Controller();
        if(!$this->session->userdata('logged_in'))
            redirect('/home/');
        $this->lang->load('general',$this->lenguaje);
    }


    /**
     * Muestra las castegorias
     */
    function index() {
        $id  = $this->uri->segment(4);
        $sub = $this->uri->segment(5);
        $datos['titulo_pagina'] = 'Categorias';
        $this->load->view('admin/encabezado_admin.php', $datos);
        $this->load->view('admin/menu_admin.php');
        $this->load->model('categorias/modelo_categorias');
        $query = $this->modelo_categorias->get_categorias();
        $query['id']  = $id;
        $query['sub'] = $sub;
        $this->load->view('admin/categorias',$query);
        $this->load->view('admin/pie_admin.php');
    }

    /**
     * Pasa datos por Json a la tabla de categorias
     */
    function post() {
        $tabla       = "category";
        $page        = $this->input->post('page');
        $limit       = $this->input->post('rows');
        $sidx        = $this->input->post('sidx');
        $sord        = $this->input->post('sord');
        $_search     = $this->input->post('_search');
        $searchField = $this->input->post('searchField');
        $searchString= $this->input->post('searchString');

        $where = "";
        if ($_search=='true')
            $where = " WHERE $searchField LIKE '%$searchString%' ";


        if(!$sidx) $sidx =1;

        $sql    = "SELECT * FROM $tabla $where";
        //echo $sql;
        $query  = $this->db->query($sql);
        $result = $query->result();

        $count  = count($result);

        if( $count > 0 && $limit > 0) {
            $total_pages = ceil($count/$limit);
        } else {
            $total_pages = 0;
        }

        if ($page > $total_pages) $page=$total_pages;
        $start = $limit*$page - $limit;
        if($start <0) $start = 0;
        $sql = "SELECT category_id, category_name, category_flypage, products_per_row, products_per_row_1,impuestos FROM category INNER JOIN category_xref on category.category_id=category_xref.category_child_id where category_xref.category_parent_id=0";
        $query  = $this->db->query($sql);

        header("Expires: Mon, 26 Jul 1997 05:00:00 GMT" );
        header("Last-Modified: " . gmdate( "D, d M Y H:i:s" ) . "GMT" );
        header("Cache-Control: no-cache, must-revalidate" );
        header("Pragma: no-cache" );
        header("Content-type: text/x-json");
        $i=0;
        $data['page']= $page;
        $data['total']= $total_pages;

        foreach ($query->result() as $row) {
            $data['rows'][$i]['id']= $row->category_id;
            $data['rows'][$i]['cell'][]= $row->category_id;
            $data['rows'][$i]['cell'][]= $row->category_name;
            $data['rows'][$i]['cell'][]= $row->category_flypage;
            $data['rows'][$i]['cell'][]= $row->products_per_row;
            $data['rows'][$i]['cell'][]= $row->products_per_row_1;
            $data['rows'][$i]['cell'][]= $row->impuestos;

            $sql = "SELECT idioma, category_desc from category_text where category_id=".$row->category_id;
            $query  = $this->db->query($sql);

            foreach ($query->result() as $raw) {
                //$data['rows'][$i]['cell'][]= utf8_encode($raw->idioma);
                $data['rows'][$i]['cell'][]= utf8_encode($raw->category_desc);
            }

            $i++;
        }
        echo json_encode($data);
    }

    /**
     * Pasa datos por Json a la tabla de sub-categorias
     */
    function post1() {
        $tabla       = "category";
        $page        = $this->input->post('page');
        $limit       = $this->input->post('rows');
        $sidx        = $this->input->post('sidx');
        $sord        = $this->input->post('sord');
        $_search     = $this->input->post('_search');
        $searchField = $this->input->post('searchField');
        $searchString= $this->input->post('searchString');
        $id          = $this->uri->segment(4);


        $where = "";
        if ($_search=='true')
            $where = " WHERE $searchField LIKE '%$searchString%' ";


        if(!$sidx) $sidx =1;

        $sql    = "SELECT * FROM $tabla $where";
        //echo $sql;
        $query  = $this->db->query($sql);
        $result = $query->result();

        $count  = count($result);

        if( $count > 0 && $limit > 0) {
            $total_pages = ceil($count/$limit);
        } else {
            $total_pages = 0;
        }

        if ($page > $total_pages) $page=$total_pages;
        $start = $limit*$page - $limit;
        if($start <0) $start = 0;
        $sql = "SELECT category_id, category_name, category_flypage, products_per_row, products_per_row_1 FROM category INNER JOIN category_xref on category.category_id=category_xref.category_child_id where category_xref.category_parent_id=".$id;
        $query  = $this->db->query($sql);

        header("Expires: Mon, 26 Jul 1997 05:00:00 GMT" );
        header("Last-Modified: " . gmdate( "D, d M Y H:i:s" ) . "GMT" );
        header("Cache-Control: no-cache, must-revalidate" );
        header("Pragma: no-cache" );
        header("Content-type: text/x-json");
        $i=0;
        $data['page']= $page;
        $data['total']= $total_pages;

        foreach ($query->result() as $row) {
            $data['rows'][$i]['id']= $row->category_id;
            $data['rows'][$i]['cell'][]= $row->category_id;
            $data['rows'][$i]['cell'][]= $row->category_name;
            $data['rows'][$i]['cell'][]= $row->category_flypage;
            $data['rows'][$i]['cell'][]= $row->products_per_row;
            $data['rows'][$i]['cell'][]= $row->products_per_row_1;


            $sql = "SELECT idioma, category_desc from category_text where category_id=".$row->category_id;
            $query  = $this->db->query($sql);

            foreach ($query->result() as $raw) {
                //$data['rows'][$i]['cell'][]= utf8_encode($raw->idioma);
                $data['rows'][$i]['cell'][]= utf8_encode($raw->category_desc);
            }

            $i++;
        }
        echo json_encode($data);
    }

    /**
     * Pasa datos por Json a la tabla de productos
     */
    function post2() {
        $tabla       = "category";
        $page        = $this->input->post('page');
        $limit       = $this->input->post('rows');
        $sidx        = $this->input->post('sidx');
        $sord        = $this->input->post('sord');
        $_search     = $this->input->post('_search');
        $searchField = $this->input->post('searchField');
        $searchString= $this->input->post('searchString');
        $id = $this->uri->segment(4);

        $where = "";
        if ($_search=='true')
            $where = " WHERE $searchField LIKE '%$searchString%' ";

        if(!$sidx) $sidx =1;

        $sql    = "SELECT * FROM $tabla $where";
        //echo $sql;
        $query  = $this->db->query($sql);
        $result = $query->result();

        $count  = count($result);

        if( $count > 0 && $limit > 0) {
            $total_pages = ceil($count/$limit);
        } else {
            $total_pages = 0;
        }

        if ($page > $total_pages) $page=$total_pages;
        $start = $limit*$page - $limit;
        if($start <0) $start = 0;
        $sql = "SELECT product.product_id,product_publish,product_sku,product_desc,product_name,product_in_stock,product_weight,product_weight_uom,product_lwh_uom,product_width,product_height,product_full_image,product_discount_id,custom_attribute,cdate,mdate FROM product INNER JOIN product_category_xref on product.product_id=product_category_xref.product_id where product_category_xref.category_id=".$id;
        $query  = $this->db->query($sql);

        header("Expires: Mon, 26 Jul 1997 05:00:00 GMT" );
        header("Last-Modified: " . gmdate( "D, d M Y H:i:s" ) . "GMT" );
        header("Cache-Control: no-cache, must-revalidate" );
        header("Pragma: no-cache" );
        header("Content-type: text/x-json");
        $i=0;
        $data['page']= $page;
        $data['total']= $total_pages;

        foreach ($query->result() as $row) {
            $data['rows'][$i]['id']= $row->product_id;
            $data['rows'][$i]['cell'][]= $row->product_id;
            $data['rows'][$i]['cell'][]= $row->product_publish;
            $data['rows'][$i]['cell'][]= $row->product_sku;
            $data['rows'][$i]['cell'][]= $row->product_desc;
            $data['rows'][$i]['cell'][]= $row->product_name;
            $data['rows'][$i]['cell'][]= $row->product_in_stock;
            $data['rows'][$i]['cell'][]= $row->product_discount_id;

            $query = $this->db->query("SELECT product_price FROM product_price WHERE product_id='".$row->product_id."'");
            if ($query->num_rows() > 0) {
                $ruw=$query->row();
                $data['rows'][$i]['cell'][]= $ruw->product_price;
            }

            $data['rows'][$i]['cell'][]= '<a href="'.base_url().'index.php/admin/categorias/upload_image/'.$row->product_id.'"><img style="border-color : #000000; border-style : dashed; border-width : 1px;" src="'.base_url().'thumb/'.$row->product_id.'.jpg" alt="Imagen" title="Imagen" /></a>';
            $data['rows'][$i]['cell'][]= $row->product_full_image;

            $sql = "SELECT idioma, product_s_desc, product_desc from product_text where product_id=".$row->product_id;
            $query  = $this->db->query($sql);

            foreach ($query->result() as $raw) {
                //$data['rows'][$i]['cell'][]= utf8_encode($raw->idioma);
                $data['rows'][$i]['cell'][]= $raw->product_s_desc;
                $data['rows'][$i]['cell'][]= $raw->product_desc;
            }

            $i++;
        }
        echo json_encode($data);
    }

    /**
     * ABM de Categorias
     */
    function guardar() {
        $oper               = $this->input->post('oper');
        $category_id        = $this->input->post('id');
        $category_name      = $this->input->post('category_name');
        $category_flypage   = $this->input->post('category_flypage');
        $products_per_row   = $this->input->post('products_per_row');
        $products_per_row_1 = $this->input->post('products_per_row_1');
        $impuestos          = $this->input->post('impuestos');
        $english            = $this->input->post('english');
        $spanish            = $this->input->post('spanish');
        $italy              = $this->input->post('italy');
        $portugues          = $this->input->post('portugues');
        $category_parent_id = $category_id;
        $timestamp = time();  // Let's find out the last category in the level of the new category

        if($oper=='edit') {
            // Modify category_flypage
            $q  = "UPDATE category set category_flypage='";
            $q .= $category_flypage . "',";
            $q .= "products_per_row='".$products_per_row . "',";
            $q .= "products_per_row_1='".$products_per_row_1 . "',";
            $q .= "impuestos='".$impuestos . "'";
            $q .= " WHERE category_id=".$category_id;
            echo $q;
            $this->db->query($q);

            // Modify descriptions large Español
            $q  = "UPDATE category_text set category_desc='";
            $q .= $spanish . "' WHERE idioma='spanish' AND category_id=".$category_id;
            $this->db->query($q);

            // Modify descriptions large English
            $q  = "UPDATE category_text set category_desc='";
            $q .= $english . "' WHERE idioma='english' AND category_id=".$category_id;
            $this->db->query($q);

            // Modify descriptions large Italy
            $q  = "UPDATE category_text set category_desc='";
            $q .= $italy . "' WHERE idioma='italy' AND category_id=".$category_id;
            $this->db->query($q);

            // Modify descriptions large Portugues
            $q  = "UPDATE category_text set category_desc='";
            $q .= $portugues . "' WHERE idioma='portugues' AND category_id=".$category_id;
            $this->db->query($q);
        }elseif($oper=='add') {
            // Add category
            $q = "INSERT INTO category ";
            $q .= "(vendor_id,category_name, category_publish,cdate,mdate,list_order,category_flypage,products_per_row,products_per_row_1,impuestos) ";
            $q .= "VALUES ('";
            $q .= "1', '";
            $q .= $category_name . "', '";
            $q .= "Y', '";
            $q .= $timestamp . "', '";
            $q .= $timestamp . "', '1','$category_flypage','$products_per_row','$products_per_row_1','$impuestos')";
            $query = $this->db->query($q);

            // Get the product ID we just created
            $category_id = $this->db->insert_id();

            // Add descriptions short and large Español
            $q  = "INSERT INTO category_text (";
            $q .= "category_id,";
            $q .= "idioma,";
            $q .= "category_desc)";
            $q .= "VALUES ('";
            $q .= $category_id . "','";
            $q .= "spanish','";
            $q .= $spanish . "')";
            $this->db->query($q);

            // Add descriptions short and large Ingles
            $q  = "INSERT INTO category_text (";
            $q .= "category_id,";
            $q .= "idioma,";
            $q .= "category_desc)";
            $q .= "VALUES ('";
            $q .= $category_id . "','";
            $q .= "english','";
            $q .= $english . "')";
            $this->db->query($q);

            // Add descriptions short and large Italiano
            $q  = "INSERT INTO category_text (";
            $q .= "category_id,";
            $q .= "idioma,";
            $q .= "category_desc)";
            $q .= "VALUES ('";
            $q .= $category_id . "','";
            $q .= "italy','";
            $q .= $italy . "')";
            $this->db->query($q);

            // Add descriptions short and large Portugues
            $q  = "INSERT INTO category_text (";
            $q .= "category_id,";
            $q .= "idioma,";
            $q .= "category_desc)";
            $q .= "VALUES ('";
            $q .= $category_id . "','";
            $q .= "portugues','";
            $q .= $portugues . "')";
            $this->db->query($q);

            // Create xref with parent
            $q = "INSERT INTO category_xref ";
            $q .= "(category_parent_id, category_child_id) ";
            $q .= "VALUES ('";
            $q .= $category_parent_id . "', '";
            $q .= $category_id . "')";
            $query = $this->db->query($q);

        }elseif($oper=='del') {
            /**
             * ver bien esto :-)
             */
            //Elimina Categoria
            $query = $this->db->query("DELETE FROM category WHERE category_id=$category_id");
            //echo $this->db->last_query();

            //Elimina Sub Categoria
            $query = $this->db->query("DELETE FROM category_xref WHERE category_parent_id=$category_id");

            $query = $this->db->query("DELETE FROM category_text WHERE category_id=category_id");
            $query = $this->db->query("DELETE FROM category_xref WHERE category_child_id=$category_id");

            $sql = "SELECT product_id from product_category_xref where category_id=".$row->category_id;
            $query  = $this->db->query($sql);
            foreach ($query->result() as $raw) {
                $query = $this->db->query("DELETE FROM product WHERE product_id=$raw->product_id");
            }

        }
    }

    /**
     * ABM de Sub-categorias
     */
    function guardar1() {
        $oper               = $this->input->post('oper');
        $category_id        = $this->input->post('id');
        $category_name      = $this->input->post('category_name');
        $category_flypage   = $this->input->post('category_flypage');
        $products_per_row   = $this->input->post('products_per_row');
        $products_per_row_1 = $this->input->post('products_per_row_1');
        $english            = $this->input->post('english');
        $spanish            = $this->input->post('spanish');
        $italy              = $this->input->post('italy');
        $portugues          = $this->input->post('portugues');
        $id = $this->uri->segment(4);
        $category_parent_id = $id;
        $timestamp = time();  // Let's find out the last category in the level of the new category

        if($oper=='edit') {
            // Modify category_flypage
            $q  = "UPDATE category set category_flypage='";
            $q .= $category_flypage . "',";
            $q .= "products_per_row='".$products_per_row . "',";
            $q .= "products_per_row_1='".$products_per_row_1 . "'";
            $q .= " WHERE category_id=".$category_id;
            //echo $q;
            $this->db->query($q);

            // Modify descriptions large Español
            $q  = "UPDATE category_text set category_desc='";
            $q .= $spanish . "' WHERE idioma='spanish' AND category_id=".$category_id;
            $this->db->query($q);

            // Modify descriptions large English
            $q  = "UPDATE category_text set category_desc='";
            $q .= $english . "' WHERE idioma='english' AND category_id=".$category_id;
            $this->db->query($q);

            // Modify descriptions large Italy
            $q  = "UPDATE category_text set category_desc='";
            $q .= $italy . "' WHERE idioma='italy' AND category_id=".$category_id;
            $this->db->query($q);

            // Modify descriptions large Portugues
            $q  = "UPDATE category_text set category_desc='";
            $q .= $portugues . "' WHERE idioma='portugues' AND category_id=".$category_id;
            $this->db->query($q);
        }elseif($oper=='add') {
            // Add category
            $q = "INSERT INTO category ";
            $q .= "(vendor_id,category_name, category_publish,cdate,mdate,list_order,category_flypage) ";
            $q .= "VALUES ('";
            $q .= "1', '";
            $q .= $category_name . "', '";
            $q .= "Y', '";
            $q .= $timestamp . "', '";
            $q .= $timestamp . "', '1', '$category_flypage')";
            $query = $this->db->query($q);

            // Get the product ID we just created
            $category_id = $this->db->insert_id();

            // Add descriptions short and large Español
            $q  = "INSERT INTO category_text (";
            $q .= "category_id,";
            $q .= "idioma,";
            $q .= "category_desc)";
            $q .= "VALUES ('";
            $q .= $category_id . "','";
            $q .= "spanish','";
            $q .= $spanish . "')";
            $this->db->query($q);

            // Add descriptions short and large Ingles
            $q  = "INSERT INTO category_text (";
            $q .= "category_id,";
            $q .= "idioma,";
            $q .= "category_desc)";
            $q .= "VALUES ('";
            $q .= $category_id . "','";
            $q .= "english','";
            $q .= $english . "')";
            $this->db->query($q);

            // Add descriptions short and large Italiano
            $q  = "INSERT INTO category_text (";
            $q .= "category_id,";
            $q .= "idioma,";
            $q .= "category_desc)";
            $q .= "VALUES ('";
            $q .= $category_id . "','";
            $q .= "italy','";
            $q .= $italy . "')";
            $this->db->query($q);

            // Add descriptions short and large Portugues
            $q  = "INSERT INTO category_text (";
            $q .= "category_id,";
            $q .= "idioma,";
            $q .= "category_desc)";
            $q .= "VALUES ('";
            $q .= $category_id . "','";
            $q .= "portugues','";
            $q .= $portugues . "')";
            $this->db->query($q);

            // Create xref with parent
            $q = "INSERT INTO category_xref ";
            $q .= "(category_parent_id, category_child_id) ";
            $q .= "VALUES ('";
            $q .= $category_parent_id . "', '";
            $q .= $category_id . "')";
            $query = $this->db->query($q);

        }elseif($oper=='del') {
            $query = $this->db->query("DELETE FROM category WHERE category_id=$category_id");
            $query = $this->db->query("DELETE FROM category_xref WHERE category_child_id=$category_id");
        }
    }

    /**
     * ABM de Productos
     */
    function guardar2() {
        $oper               = $this->input->post('oper');
        //$category_id        = $this->input->post('id');
        $category_name      = $this->input->post('category_name');
        $category_flypage   = $this->input->post('category_flypage');
        $english            = $this->input->post('english');
        $spanish            = $this->input->post('spanish');
        $italy              = $this->input->post('italy');
        $portugues          = $this->input->post('portugues');

        $product_publish    = $this->input->post('product_publish');
        $product_sku        = $this->input->post('product_sku');
        $product_desc       = $this->input->post('product_desc');
        $product_name       = $this->input->post('product_name');
        $product_in_stock   = $this->input->post('product_in_stock');
        $product_discount_id= $this->input->post('product_discount_id');

        $product_full_image = $this->input->post('product_full_image');
        $spanish_s          = $this->input->post('spanish_s');
        $spanish            = $this->input->post('spanish');
        $english_s          = $this->input->post('english_s');
        $english            = $this->input->post('english');
        $italy_s            = $this->input->post('italy_s');
        $italy              = $this->input->post('italy');
        $portugues_s        = $this->input->post('portugues_s');
        $portugues          = $this->input->post('portugues');
        $product_price      = $this->input->post('product_price');

        $category_id = $this->uri->segment(4);
        $product_id = $this->input->post('id');
        $timestamp = time();  // Let's find out the last category in the level of the new category

        if($oper=='add') {

            $timestamp = time();

            // Add product information
            $q  = "INSERT INTO product (";
            $q .= "product_publish,";
            $q .= "product_sku,";
            $q .= "product_desc,";
            $q .= "product_name,";
            $q .= "product_in_stock,";
            $q .= "product_full_image,";
            $q .= "product_discount_id) ";

            $q .= "VALUES ('".$product_publish . "','";
            $q .= $product_sku . "','";
            $q .= $product_desc . "','";
            $q .= $product_name . "','";
            $q .= $product_in_stock . "','";
            $q .= $product_full_image . "','";
            $q .= $product_discount_id . "')";
            $this->db->query($q);
            // echo $this->db->last_query();

            // Get the product ID we just created
            $product_id = $this->db->insert_id();

            // Add descriptions short and large Español
            $q  = "INSERT INTO product_text (";
            $q .= "product_id,";
            $q .= "idioma,";
            $q .= "product_s_desc,";
            $q .= "product_desc)";
            $q .= "VALUES ('";
            $q .= $product_id . "','";
            $q .= "spanish','";
            $q .= $spanish_s . "','";
            $q .= $spanish . "')";
            $this->db->query($q);

            // Add descriptions short and large Ingles
            $q  = "INSERT INTO product_text (";
            $q .= "product_id,";
            $q .= "idioma,";
            $q .= "product_s_desc,";
            $q .= "product_desc)";
            $q .= "VALUES ('";
            $q .= $product_id . "','";
            $q .= "english','";
            $q .= $english_s . "','";
            $q .= $english . "')";
            $this->db->query($q);

            // Add descriptions short and large Italiano
            $q  = "INSERT INTO product_text (";
            $q .= "product_id,";
            $q .= "idioma,";
            $q .= "product_s_desc,";
            $q .= "product_desc)";
            $q .= "VALUES ('";
            $q .= $product_id . "','";
            $q .= "italy','";
            $q .= $italy_s . "','";
            $q .= $italy . "')";
            $this->db->query($q);

            // Add descriptions short and large Portugues
            $q  = "INSERT INTO product_text (";
            $q .= "product_id,";
            $q .= "idioma,";
            $q .= "product_s_desc,";
            $q .= "product_desc)";
            $q .= "VALUES ('";
            $q .= $product_id . "','";
            $q .= "portugues','";
            $q .= $portugues_s . "','";
            $q .= $portugues . "')";
            $this->db->query($q);

            // Add precio
            $precio = str_replace(',','.',addslashes($product_price));
            $q = "INSERT INTO product_price ";
            $q .= "(product_price, ";
            $q .= "product_id, ";
            $q .= "product_currency, ";
            $q .= "currency_id, ";
            $q .= "shopper_group_id, ";
            $q .= "cant_min, ";
            $q .= "mdate) VALUES ('";
            $q .= $precio. "','";
            $q .= $product_id . "','";
            $q .= "1','";
            $q .= "1','";
            $q .= "1','";
            $q .= "1','";
            $q .= $timestamp . "') ";
            $this->db->query($q);

            // Add referencia
            $q  = "INSERT INTO product_category_xref (category_id, product_id ) VALUES (";
            $q .= "'$category_id', '$product_id')";
            $this->db->query($q);


        }elseif($oper=='del') {
            $query = $this->db->query("DELETE FROM product WHERE product_id=$product_id");
            $query = $this->db->query("DELETE FROM product_category_xref WHERE product_id=$product_id");
            $query = $this->db->query("DELETE FROM product_text WHERE product_id=$product_id");
        }else {
            // Update product information
            $q  = "UPDATE product set ";
            $q .= "product_publish='".$product_publish."',";
            $q .= "product_sku='".$product_sku."',";
            $q .= "product_desc='".$product_desc."',";
            $q .= "product_name='".$product_name."',";
            $q .= "product_in_stock='".$product_in_stock."',";
            $q .= "product_full_image='".$product_full_image."',";
            $q .= "product_discount_id='".$product_discount_id."'";
            $q .= " WHERE product_id=".$product_id;
            $this->db->query($q);

            // Update descriptions short and large Español
            $q  = "UPDATE product_text set ";
            $q .= "product_s_desc='".$spanish_s."',";
            $q .= "product_desc='".$spanish."'";
            $q .= " WHERE idioma='spanish' AND product_id=".$product_id;
            $this->db->query($q);

            // Update descriptions short and large English
            $q  = "UPDATE product_text set ";
            $q .= "product_s_desc='".$english_s."',";
            $q .= "product_desc='".$english."'";
            $q .= " WHERE idioma='english' AND product_id=".$product_id;
            $this->db->query($q);

            // Update descriptions short and large Italy
            $q  = "UPDATE product_text set ";
            $q .= "product_s_desc='".$italy_s."',";
            $q .= "product_desc='".$italy."'";
            $q .= " WHERE idioma='italy' AND product_id=".$product_id;
            $this->db->query($q);

            // Update descriptions short and large Portugues
            $q  = "UPDATE product_text set ";
            $q .= "product_s_desc='".$portugues_s."',";
            $q .= "product_desc='".$portugues."'";
            $q .= " WHERE idioma='portugues' AND product_id=".$product_id;
            $this->db->query($q);

            // Update precio
            $precio = str_replace(',','.',addslashes($product_price));
            $q = "UPDATE product_price set ";
            $q .= "product_price='".$precio."', ";
            $q .= "product_currency='1', ";
            $q .= "currency_id='1', ";
            $q .= "shopper_group_id='1', ";
            $q .= "cant_min='1', ";
            $q .= "mdate='".$timestamp."'";
            $q .= " WHERE product_id=".$product_id;
            $this->db->query($q);
//            echo $this->db->last_query();

        }
    }


    /**
     * Muestra las sub castegorias
     */
    function sub_categoria() {
        //Load the URL helper
        $datos['titulo_pagina'] = 'Sub categorias';
        $this->load->helper('url');
        $this->load->helper(array('form', 'url'));
        $id = $this->uri->segment(4);
        $id_category = $this->uri->segment(5);
        $this->load->view('admin/encabezado_admin.php', $datos);
        $this->load->view('admin/menu_admin.php');
        $this->load->model('/categorias/modelo_categorias');
        $this->load->model('/ec/modelo_ec');
        $query['producto']=$id;
        $query['category']=$id_category;
        $this->load->view('admin/sub_categorias', $query);
        $this->load->view('admin/pie_admin.php');
    }




    /**
     * Muestra lista de productos
     */
    function lista_de_productos() {
        //Load the URL helper
        $this->load->helper('url');
        $this->load->helper(array('form', 'url'));
        $id = $this->uri->segment(4 );
        $datos['titulo_pagina'] = 'Productos';
        $this->load->view('admin/encabezado_admin', $datos);
        $this->load->view('admin/menu_admin.php');
        $this->load->model('categorias/modelo_categorias'); //carga modelo
        $this->load->model('ec/modelo_ec'); //carga modelo
        $query['consulta'] = $this->db->query("SELECT * FROM product_category_xref WHERE category_id =$id");

        $query['categoria']=$id;
        $this->load->view('admin/lista_de_productos', $query);
        $this->load->view('admin/pie.php');
    }

    function importar1() {
        $importar_file_articulos = $this->input->post('importar_file_articulos');
        $product_sku = $this->input->post('product_sku');
        $product_name = $this->input->post('product_name');
        $product_in_stock = $this->input->post('product_in_stock');

        $product_weight = $this->input->post('product_weight');
        $product_weight_uom = $this->input->post('product_weight_uom');
        $product_lwh_uom = $this->input->post('product_lwh_uom');
        $product_width = $this->input->post('product_width');
        $product_height = $this->input->post('product_height');

        $i =0;
        $timestamp = time();
        // Add product information
        $q  = "INSERT INTO product (";
        $q .= "vendor_id,product_parent_id,product_publish,";
        $q .= "product_sku,";
        $q .= "product_name,";
        $q .= "product_in_stock,";

        $q .= "product_weight,";
        $q .= "product_weight_uom,";
        $q .= "product_lwh_uom,";
        $q .= "product_width,";
        $q .= "product_height,";

        $q .= "cdate,";
        $q .= "mdate) ";
        $q .= "VALUES ('1','0','Y','";
        $q .= $product_sku . "','";
        $q .= $product_name . "','";
        $q .= $product_in_stock . "','";

        $q .= $product_weight . "','";
        $q .= $product_weight_uom . "','";
        $q .= $product_lwh_uom . "','";
        $q .= $product_width . "','";
        $q .= $product_height . "','";
        $q .= "$timestamp','";
        $q .= "$timestamp');";
        $this->db->query($q);

        // Get the product ID we just created
        $product_id = $this->db->insert_id();

        // Use csv_category() method to confirm/add category tree for this product
        if($data[2]<>'') {
            if($data[3]<>'') {
                if($data[4]<>'') {
                    $category_id = $this->csv_category($data[2]."/".$data[3]."/".$data[4]);
                }else {
                    $category_id = $this->csv_category($data[2]."/".$data[3]);
                }
            }else {
                $category_id = $this->csv_category($data[2]);
            }
        }

        // Insert new product/category relationships
        //		echo "category_id:";
        foreach( $category_id as $value ) {
            $q  = "INSERT INTO product_category_xref (category_id, product_id ) VALUES (";
            $q .= "'$value', '$product_id')";
            $this->db->query($q);
            //		echo $value.", ";
        }
        //		echo "<br>";

        // Get default shopper group ID
        $q = "SELECT shopper_group_id FROM shopper_group ";
        $q .= "WHERE `default`='1'";
        $query = $this->db->query($q);
        $grupo = $query->row();

        $q = "DELETE FROM product_price WHERE ";
        $q .= "product_id = '$product_id'";
        $this->db->query($q);

        for($p=1;$p<=5;$p++) {
            //		echo(" csv_cant_min_$p ");
            if(1) {
                $q = "INSERT INTO product_price ";
                $q .= "(product_price, ";
                $q .= "product_id, ";
                $q .= "product_currency, ";
                $q .= "currency_id, ";
                $q .= "shopper_group_id, ";
                $q .= "cant_min, ";
                $q .= "mdate) VALUES ('";
                $q .= str_replace(',','.',addslashes($data[8])). "','";
                $q .= $product_id . "','";
                $q .= "1','";
                $q .= "1','";
                $q .= $grupo->shopper_group_id . "','";
                $q .= "1','";
                $q .= $timestamp . "') ";
            }
            $this->db->query($q);
        }

        // Add report for this line to message
        $error  = 'Errr';
        //$error  = $dbcat->getErrorMsg();
        // $error .= $dbu->getErrorMsg();
        //$error .= $dbpp->getErrorMsg();

        $i++;
        if(($i%10)==0) {
            echo "<script>document.getElementById('contador').innerHTML='Se importaron: ".$i." Articulos';</script>";
            //  forceFlush();
        }


        //unlink($mosConfig_absolute_path."/administrator/components/com_pshop/sincronizar/importar/PET13VEN.TXT");
    }// fin "if" clientes)

    function csv_category($line) {
        $this->load->helper('text');
        $categories = explode("/", $line);
        $category_parent_id = '0';
        foreach( $categories as $line ) {
            // Explode slash delimited category tree into array
            $category_list      = explode("/", $line);
            $category_count     = count($category_list);
            $nombre             = $this->input->post('nombre');
            $category_flypage   = $this->input->post('category_flypage');
            // For each category in array
            for($i = 0; $i < $category_count; $i++) {
                // See if this category exists with it's parent in xref
                $q = "SELECT category.category_id FROM category, category_xref ";
                $q .= "WHERE category.category_name='" . $category_list[$i] . "' ";
                $q .= "AND category_xref.category_child_id=category.category_id ";
                $q .= "AND category_xref.category_parent_id='".$category_parent_id."'";
                $query = $this->db->query($q);
                $fila = $query->row();
                //echo $nombre.$query->num_rows();

                // If it does not exist, create it
                if ($query->num_rows() > 0) { // Category exists
                    $category_id = $fila->category_id;
                    if (isset($nombre)) {
                        // Modify category_flypage
                        $q  = "UPDATE category set category_flypage='";
                        $q .= $this->input->post('category_flypage') . "' WHERE category_id=".$category_id;
                        //echo $q;
                        $this->db->query($q);

                        // Modify descriptions large Español
                        $q  = "UPDATE category_text set category_desc='";
                        if ($this->input->post('sub_nombre')=='') {
                            $q .= $this->input->post('nombre') . "' WHERE idioma='spanish' AND category_id=".$category_id;
                        }else {
                            $q .= $this->input->post('sub_nombre') . "' WHERE idioma='spanish' AND category_id=".$category_id;
                        }
                        $this->db->query($q);

                        // Modify descriptions large English
                        $q  = "UPDATE category_text set category_desc='";
                        $q .= $this->input->post('nombre_en') . "' WHERE idioma='english' AND category_id=".$category_id;
                        $this->db->query($q);

                        // Modify descriptions large Italy
                        $q  = "UPDATE category_text set category_desc='";
                        $q .= $this->input->post('nombre_it') . "' WHERE idioma='italy' AND category_id=".$category_id;
                        $this->db->query($q);

                        // Modify descriptions large Portugues
                        $q  = "UPDATE category_text set category_desc='";
                        $q .= $this->input->post('nombre_pt') . "' WHERE idioma='portugues' AND category_id=".$category_id;
                        $this->db->query($q);
                    }

                } else { // Category does not exist - create it $hash_secret="PHPShopIsCool";   $category_id = md5(uniqid($hash_secret));
                    if ($category_list[$i] !='') {
                        $timestamp = time();  // Let's find out the last category in the level of the new category
                        $q = "SELECT MAX(list_order) AS list_order FROM category_xref,category ";
                        $q .= "WHERE category_parent_id='".$category_parent_id."' ";
                        $q .= "AND category_child_id=category_id ";
                        $query = $this->db->query($q);
                        $fila = $query->row();
                        $list_order = intval($fila->list_order)+1;

                        // Add category
                        $q = "INSERT INTO category ";
                        $q .= "(vendor_id,category_name, category_publish,cdate,mdate,list_order,category_flypage) ";
                        $q .= "VALUES ('";
                        $q .= "1', '";
                        $q .= $category_list[$i] . "', '";
                        $q .= "Y', '";
                        $q .= $timestamp . "', '";
                        $q .= $timestamp . "', '$list_order', '$category_flypage')";
                        $query = $this->db->query($q);

                        // Get the product ID we just created
                        $category_id = $this->db->insert_id();

                        // Add descriptions short and large Español
                        $q  = "INSERT INTO category_text (";
                        $q .= "category_id,";
                        $q .= "idioma,";
                        $q .= "category_desc)";
                        $q .= "VALUES ('";
                        $q .= $category_id . "','";
                        $q .= "spanish','";
                        if ($this->input->post('sub_nombre')=='') {
                            $q .= $this->input->post('nombre') . "')";
                        }else {
                            $q .= $this->input->post('sub_nombre') . "')";
                        }
                        $this->db->query($q);

                        // Add descriptions short and large Ingles
                        $q  = "INSERT INTO category_text (";
                        $q .= "category_id,";
                        $q .= "idioma,";
                        $q .= "category_desc)";
                        $q .= "VALUES ('";
                        $q .= $category_id . "','";
                        $q .= "english','";
                        $q .= $this->input->post('nombre_en') . "')";
                        $this->db->query($q);

                        // Add descriptions short and large Italiano
                        $q  = "INSERT INTO category_text (";
                        $q .= "category_id,";
                        $q .= "idioma,";
                        $q .= "category_desc)";
                        $q .= "VALUES ('";
                        $q .= $category_id . "','";
                        $q .= "italy','";
                        $q .= $this->input->post('nombre_it') . "')";
                        $this->db->query($q);

                        // Add descriptions short and large Portugues
                        $q  = "INSERT INTO category_text (";
                        $q .= "category_id,";
                        $q .= "idioma,";
                        $q .= "category_desc)";
                        $q .= "VALUES ('";
                        $q .= $category_id . "','";
                        $q .= "portugues','";
                        $q .= $this->input->post('nombre_pt') . "')";
                        $this->db->query($q);

                        // Create xref with parent
                        $q = "INSERT INTO category_xref ";
                        $q .= "(category_parent_id, category_child_id) ";
                        $q .= "VALUES ('";
                        $q .= $category_parent_id . "', '";
                        $q .= $category_id . "')";
                        $query = $this->db->query($q);
                    }
                }
                // Set this category as parent of next in line
                if (isset($category_id)) {
                    $category_parent_id = $category_id;
                }else {
                    $category_parent_id = 0;
                }
            } // end for
        }
        $category[] = $category_id;
        //		 echo "id:". $category_parent_id."<br><br><br>";
        // Return an array with the last category_ids which is where the product goes
        return $category;

    }


##########################################################################################################
# IMAGE FUNCTIONS																						 #
# You do not need to alter these functions																 #
##########################################################################################################
    function resizeImage($image,$width,$height,$scale) {
        list($imagewidth, $imageheight, $imageType) = getimagesize($image);
        $imageType = image_type_to_mime_type($imageType);
        $newImageWidth = ceil($width * $scale);
        $newImageHeight = ceil($height * $scale);
        $newImage = imagecreatetruecolor($newImageWidth,$newImageHeight);
        switch($imageType) {
            case "image/gif":
                $source=imagecreatefromgif($image);
                break;
            case "image/pjpeg":
            case "image/jpeg":
            case "image/jpg":
                $source=imagecreatefromjpeg($image);
                break;
            case "image/png":
            case "image/x-png":
                $source=imagecreatefrompng($image);
                break;
        }
        imagecopyresampled($newImage,$source,0,0,0,0,$newImageWidth,$newImageHeight,$width,$height);

        switch($imageType) {
            case "image/gif":
                imagegif($newImage,$image);
                break;
            case "image/pjpeg":
            case "image/jpeg":
            case "image/jpg":
                imagejpeg($newImage,$image,90);
                break;
            case "image/png":
            case "image/x-png":
                imagepng($newImage,$image);
                break;
        }

        chmod($image, 0777);
        return $image;
    }

//You do not need to alter these functions
    function resizeThumbnailImage($thumb_image_name, $image, $width, $height, $start_width, $start_height, $scale) {
        list($imagewidth, $imageheight, $imageType) = getimagesize($image);
        $imageType = image_type_to_mime_type($imageType);

        $newImageWidth = ceil($width * $scale);
        $newImageHeight = ceil($height * $scale);
        $newImage = imagecreatetruecolor($newImageWidth,$newImageHeight);
        switch($imageType) {
            case "image/gif":
                $source=imagecreatefromgif($image);
                break;
            case "image/pjpeg":
            case "image/jpeg":
            case "image/jpg":
                $source=imagecreatefromjpeg($image);
                break;
            case "image/png":
            case "image/x-png":
                $source=imagecreatefrompng($image);
                break;
        }
        imagecopyresampled($newImage,$source,0,0,$start_width,$start_height,$newImageWidth,$newImageHeight,$width,$height);
        switch($imageType) {
            case "image/gif":
                imagegif($newImage,$thumb_image_name);
                break;
            case "image/pjpeg":
            case "image/jpeg":
            case "image/jpg":
                imagejpeg($newImage,$thumb_image_name,90);
                break;
            case "image/png":
            case "image/x-png":
                imagepng($newImage,$thumb_image_name);
                break;
        }
        chmod($thumb_image_name, 0777);
        return $thumb_image_name;
    }

//You do not need to alter these functions
    function getHeight($image) {
        $size = getimagesize($image);
        $height = $size[1];
        return $height;
    }

//You do not need to alter these functions
    function getWidth($image) {
        $size = getimagesize($image);
        $width = $size[0];
        return $width;
    }

///////////////////////////////////////////////////
//////////////////////////////////////////////////

    function upload_image() {
        $dato['id'] = $this->uri->segment(4);
        $this->load->view('admin/upload_image',$dato);
    }

    function do_upload() {
        $config['upload_path'] = './upload/';
        $config['allowed_types'] = 'gif|jpg|png';
        // $config['max_size'] = '100';
        // $config['max_width'] = '1024';
        // $config['max_height'] = '768';

        $this->load->library('upload', $config);

        if ( ! $this->upload->do_upload()) {
            $error = array('error' => $this->upload->display_errors());
            $this->load->view('admin/upload_image', $error);
        } else {
            $data = $this->upload->data();
            $imagen= "upload/".$data['file_name'];
            //$imagen es la ruta en el servidor de la imagen subida
            //$imagen = "test/imagen.jpg";

            //$id es el nombre que queremos darle, en mi caso es el id
            // de la noticia insertada
            //$id = "3976";
            $id      = $this->input->post('id');
            $archivo = $this->input->post('nombre');

            $im = NULL;

            //dependiendo de la extensión creamos el recurso de la imagen
            if(stristr($imagen, 'jpg')) {
                $im = imagecreatefromjpeg($imagen);
            }
            if(stristr($imagen, 'gif')) {
                $im = imagecreatefromgif($imagen);
            }
            if(stristr($imagen, 'png')) {
                $im = imagecreatefrompng($imagen);
            }

            //Si el archivo tenia extensión JPG, GIF o PNG está permitido y tendremos una imagen cargada
            if($im !== NULL) {
                //El archivo se llamara
                $path="thumb/";
                $nombreth = $path . $id . $archivo . '.jpg';
                $path="mid/";
                $nombremd = $path . $id . $archivo . '.jpg';
                $path="big/";
                $nombre = $path . $id . $archivo . '.jpg';

                //Primero creamos la imagen grande. Nuestros limites son 500px de alto y 800px de ancho
                if(imagesy($im) > 600) {
                    $ancho = imagesx($im) * 600 / imagesy($im);
                    $dest = imagecreatetruecolor($ancho, 600);

                    imagecopyresampled($dest, $im, 0, 0, 0, 0, $ancho, 600, imagesx($im), imagesy($im));
                    imagejpeg($dest, $nombre);
                    chmod($nombre,0777);
                    imagedestroy($dest);
                } elseif(imagesx($im) > 800) {
                    $alto = imagesy($im) * 800 / imagesx($im);
                    $dest = imagecreatetruecolor(800, $alto);

                    imagecopyresampled($dest, $im, 0, 0, 0, 0, 800, $alto, imagesx($im), imagesy($im));
                    imagejpeg($dest, $nombre, 90);
                    chmod($nombre,0777);
                    imagedestroy($dest);
                } else {
                    imagejpeg($im, $nombre);
                    chmod($nombre,0777);
                }

                //La mediana creamos la imagen. Nuestros limites son 470px de alto y 397px de ancho
                if(imagesy($im) > 470) {
                    $ancho = imagesx($im) * 470 / imagesy($im);
                    $dest = imagecreatetruecolor($ancho, 470);

                    imagecopyresampled($dest, $im, 0, 0, 0, 0, $ancho, 470, imagesx($im), imagesy($im));
                    //                    imagecopyresampled($dest, $im, 0, 0, 0, 0, 397, 470, imagesx($im), imagesy($im));
                    imagejpeg($dest, $nombremd);
                    chmod($nombremd,0777);
                    imagedestroy($dest);
                } elseif(imagesx($im) > 397) {
                    $alto = imagesy($im) * 397 / imagesx($im);
                    $dest = imagecreatetruecolor(397, $alto);

                    imagecopyresampled($dest, $im, 0, 0, 0, 0, 397, $alto, imagesx($im), imagesy($im));
                    //                    imagecopyresampled($dest, $im, 0, 0, 0, 0, 397, 470, imagesx($im), imagesy($im));
                    imagejpeg($dest, $nombremd, 90);
                    chmod($nombremd,0777);
                    imagedestroy($dest);
                } else {
                    imagejpeg($im, $nombremd);
                    chmod($nombremd,0777);
                }


                //Segundo creamos la miniatura de la noticia con un ancho máximo de 71px (el alto se calcula
                // en función del ancho)
                $alto = imagesy($im) * 81 / imagesx($im);
                $dest = imagecreatetruecolor(81, $alto);

                imagecopyresampled($dest, $im, 0, 0, 0, 0, 81, $alto, imagesx($im), imagesy($im));
                imagejpeg($dest, $nombreth, 90);
                chmod($nombre,0777);
                imagedestroy($dest);
                imagedestroy($im);

                //Opcionalmente podemos borrar el archivo original y liberar espacio en disco duro
                unlink($imagen);
            }
            redirect('/admin/categorias');
            //$this->load->view('upload_success', $data);
        }
    }

}
?>